<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="exportAxi">复杂导出</el-button>
          <el-button size="small" type="danger" @click="exportSimple">简单导出</el-button>
          <el-button size="small" type="danger" @click="$router.push('/import?type=user')">excle导入</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" sortable="">
            <!-- 头像 -->
            <template slot-scope="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="height:80px"
                alt=""
                @click="showImg(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" :formatter="formOfEmployment" prop="formOfEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <!--作用域插槽  -->
            <template v-slot="{row}">
              <span>{{ row.timeOfEntry | formatDate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <!-- 作用域插槽 -->
            <template v-slot="{row}">
              <el-switch
                :value="row.enableState === 1 "
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="getRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :total="total"
            :page-size="page.size"
            layout="prev, pager, next"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 新增弹框 -->
    <add-employee :visible.sync="showDialog" />
    <!--  二维码弹框-->
    <el-dialog title="二维码" :visible.sync="showCodeDialog" @close="imgUrl=''">
      <el-row type="flex" justify="center">
        <canvas id="Canvas" />
      </el-row>
    </el-dialog>
    <!-- 角色列表框 -->
    <assign-role
      ref="assRole"
      :visible.sync="visible"
    />
  </div>
</template>

<script>
import AddEmployee from './components/add-employee'
import Employees from '@/api/constant/employees'
import { getEmployee, delEmployee } from '@/api/employees'
import { formatDate } from '@/filters'
import QRcode from 'qrcode'
import AssignRole from './components/assign-role.vue'

export default {
  components: {
    AddEmployee,
    AssignRole

  },
  data() {
    return {
      Employees, // 枚举数据
      list: [], // 存储员工
      page: {
        page: 1,
        size: 5
      },
      total: 0,
      showDialog: false, // 显示新增员工
      showCodeDialog: false, // 二维码查看弹框显示控制变量
      visible: false, // 显示角色
      imgUrl: '' // 预览头像地址
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 复杂员工导出
    async  exportAxi() {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merge = ['A1:A2', 'B1:B6', 'G1:G2']
      // 获取员工数据
      const { rows } = await getEmployee({ page: 1, total: this.total })
      // console.log(rows)

      const data = rows.map(item => {
        return Object.keys(headers).map(key => {
          // 时间处理
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          }
          // 聘用格式处理
          if (headers[key] === 'formOfEmployment') {
            const fd = Employees.hireType.find(item => item.id === item[headers[key]])
            return fd ? fd.value : '未知'
          }
          return item[headers[key]]
        })
      })
      // console.log(data)
      // 表头为数组
      const tHeader = Object.keys(headers)

      // 懒加载
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx', // 非必填
          multiHeader,
          merge
        })
      })

      this.$message.success('导出成功')
    },
    // 简单员工导出
    async  exportSimple() {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 获取员工数据
      const { rows } = await getEmployee({ page: 1, total: this.total })
      // console.log(rows)

      const data = rows.map(item => {
        return Object.keys(headers).map(key => {
          // 时间处理
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          }
          // 聘用格式处理
          if (headers[key] === 'formOfEmployment') {
            const fd = Employees.hireType.find(item => item.id === item[headers[key]])
            return fd ? fd.value : '未知'
          }
          return item[headers[key]]
        })
      })
      // console.log(data)
      // 表头为数组
      const tHeader = Object.keys(headers)

      // 懒加载
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })

      this.$message.success('导出成功')
    },
    // 删除员工
    async  delEmployee(id) {
      console.log(id)
      await this.$confirm('确定删除吗？')
      await delEmployee(id)
      this.$message.success('删除成功')
      this.getEmployeeList()
    },
    // 枚举数据 格式化数据
    formOfEmployment(row, column, cellValue, index) {
      const arr = Employees.hireType.find(item => item.id === cellValue)
      return arr ? arr.value : '未知'
    },
    // 控制页面
    async  changePage(page) {
      this.page.page = page
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const { total, rows } = await getEmployee(this.page)
      this.total = total
      this.list = rows
    },
    // 展示二维码
    showImg(val) {
      if (!val) return this.$message.warning('没有头像')
      this.showCodeDialog = true
      this.$nextTick(() => {
        const canva = document.getElementById('Canvas')
        QRcode.toCanvas(canva, val, (err) => {
          if (err) console.log('打印照片失败', err)
        })
      })
    },
    // 获取所有角色
    async  getRole(id) {
      // 获取所有角色权限
      await this.$refs.assRole.getRoleList()
      // 获取用户详情信息
      await this.$refs.assRole.getUserInfo(id)
      this.visible = true
    }

  }

}
</script>

<style>

</style>
